#!/bin/bash

P6="/dev/mmcblk0p6"
APP_PATH="/opt/middleware"

date_format="+%Y-%m-%dT%T"
UpgradgeLog="/var/alog/AtlasEdge_log/middleware.log"
CHECKMOUNT=`df -h | awk '{if($1=="/dev/mmcblk0p6"){print $6}}'`

declare -i Err_OK=0 
declare -i MountFailed=1

function setEnv()
{
   MountPath=${CHECKMOUNT}
   if [ ${MountPath} ]; then
      APP_PATH=${MountPath}
   else
      mkdir -p ${APP_PATH}
      mount ${P6} ${APP_PATH}
      if [ "$?" != "0" ]; then
         echo "$(date ${date_format}) mount failed" >> ${UpgradgeLog}
         return ${MountFailed}
      fi
   fi
   
   return 0
}

function main()
{
   echo "$(date ${date_format}) begin recovery" >> ${UpgradgeLog}
   setEnv
   ret=$?
   if [ "$ret" != 0 ]; then
      echo "$(date ${date_format}) setEnv failed" >> ${UpgradgeLog}
      return ${ret}
   fi

   echo "$(date ${date_format}) start recoverybackup" >> ${UpgradgeLog}

   ATLASEDGE_PRE_UPGRADE_PATH=${APP_PATH}/AtlasEdge/edge_upgrade
   if [ -d $ATLASEDGE_PRE_UPGRADE_PATH/ ]; then
      echo "$(date ${date_format}) del edge_upgrade" >> ${UpgradgeLog}
      rm -rf $ATLASEDGE_PRE_UPGRADE_PATH/
   fi

   HA_PRE_UPGRADE_DIR=${APP_PATH}/ha/ha_upgrade
   if [ -d $HA_PRE_UPGRADE_DIR/ ]; then
      echo "$(date ${date_format}) del ha_upgrade" >> ${UpgradgeLog}
      rm -rf $HA_PRE_UPGRADE_DIR/
   fi
   
   echo "$(date ${date_format}) finish rollback done" >> ${UpgradgeLog}
   return 0
}

main "$@"
RESULT=$?
exit $RESULT